underscore _
In Python, the underscore character _ is a special symbol that is used in several different ways depending on the context. It doesn't have just one meaning — Python programmers use it for multiple purposes. Here are the most common uses:
Temporary or "throwaway" variable
for _ in range(5):
print("Hello")
Explanation:
a, _, x = (110, 120, 30) print(a, x)output: 110 30
In the Python interactive shell, _ stores the last result. Example:
>>> 5 + 3 8 >>> _ * 2 16
Separating digits in numbers: Python allows _ to make large numbers easier to read. Example:
num = 1_000_000 print(num)
Private variables (by convention): A single underscore before a variable means "internal use". Example:
class Employee:
def __init__(self):
self._name = "Sheetal"
Special methods (double underscore): Double underscores __ are used for special Python methods. Example:
class A:
def __init__(self):
print("Object created")